package com.mingren.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.mingren.config.CosClientConfig;
import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import com.mingren.exception.ThrowUtils;
import com.mingren.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件上传服务FileManager:提供一个上传图片信息并返回图片解析的方法
 * @deprecated 已经废弃,改为使用upload包的模板方法优化
 */
@Service
@Slf4j
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1、执行校验图片逻辑
        validPicture(multipartFile);
        // 2、编辑图片上传地址
        // 2.1 UUDI
        String UUID = RandomUtil.randomString(7);
        // 2.2 获取文件源名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 3、拼接上传文件的路径
        String uploadFilename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + UUID + "." + FileUtil.getSuffix(originalFilename);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        //上传文件逻辑
        try {
            /**
             * 这行代码调用了 File 类的静态方法 createTempFile 来创建一个临时文件。
             * filepath：这个参数通常作为临时文件名称的前缀
             * 表示临时文件名称的后缀
             */
            file = File.createTempFile(uploadPath, null);
            /**
             * 将上传的文件内容从内存或临时存储位置转移到之前创建的临时文件中
             */
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取图片宽高
            int picHeight = imageInfo.getWidth();
            int picWidth = imageInfo.getHeight();
            // 计算图片宽高比例 保留两位小数
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            //脱敏返回图片信息
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename)); // 返回主文件名
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            //返回可访问的地址
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 清理临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 通过URL导入图片
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        // 1、执行校验图片逻辑
        validPicture(fileUrl);
        // 2、编辑图片上传地址
        // 2.1 UUDI
        String UUID = RandomUtil.randomString(7);
        // 2.2 获取文件源名称
        String originalFilename = FileUtil.mainName(fileUrl);
        // 3、拼接上传文件的路径
        String uploadFilename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + UUID + "." + FileUtil.getSuffix(originalFilename);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        //上传文件逻辑
        try {
            /**
             * 这行代码调用了 File 类的静态方法 createTempFile 来创建一个临时文件。
             * filepath：这个参数通常作为临时文件名称的前缀
             * 表示临时文件名称的后缀
             */
            file = File.createTempFile(uploadPath, null);
            HttpUtil.downloadFile(fileUrl, file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取图片宽高
            int picHeight = imageInfo.getWidth();
            int picWidth = imageInfo.getHeight();
            // 计算图片宽高比例 保留两位小数
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            //脱敏返回图片信息
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename)); // 返回主文件名
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            //返回可访问的地址
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 清理临时文件
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验文件接口
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        //后台校验文件大小 -> 同时需要指定Spring 的servlet上传文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2MB");
        // 2.校验文件后缀
        // 2.1获取当前文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀列表或集合
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "png", "jpg", "webp");
        //如果允许上传的文件后缀不包括fileSuffix 返回异常
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    /**
     * 检验URL接口
     */
    private void validPicture(String fileUrl) {
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        // 1、验证 URL 格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        // 2、校验URL协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("https://")) || !(fileUrl.startsWith("http://")), ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3、发送HEAD请求验证文件是否存在
        HttpResponse response = null;

        try {
            HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            //未正常返回,无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            //4、校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            //5、校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            //释放资源
            if (response != null) {
                response.close();
            }
        }
    }

    /**
     * 清理临时文件
     */
    public void deleteTempFile(File TempFile) {
        if (TempFile == null) {
            //如果文件为空直接返回
            return;
        }
        //如果文件不为空 则需要删除暂存的当前文件
        boolean deleteResult = TempFile.delete();
        if (!deleteResult) {
            //如果临时文件删除失败则打出日志失效
            log.error("file delete error, filepath = {}", TempFile.getAbsolutePath());
        }
    }
}
